﻿using Inovout.Cloud.Storage.Models;
using Inovout.Cloud.Storage.Services;
using Inovout.Cloud.Storage.Web.Models;
using Inovout.Cloud.Web.Http;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Inovout.Cloud.Storage.Web.Controllers
{

    public class BucketsController : CloudHttpController<Bucket>
    {
        IBucketService bucketService;
        public BucketsController()
        {
            this.bucketService = ComponentRegistry.Resolve<IBucketService>();
        }
        //GET https://www.googleapis.com/storage/v1beta2/b/{bucket}
        [Route("v1/b/{bucket}")] 
        public BucketInfo Get(string bucket)
        {
            return this.BindToViewModel(bucketService.FindByName(bucket));
        }
        //GET https://www.googleapis.com/storage/v1beta2/b
       [Route("v1/b/")] 
        public object Get()
        {
            return new
            {
                items =
                    ((IEnumerable<Bucket>)bucketService.FindAllByProject(base.Project)).Select(b => BindToViewModel(b))
            };
        }

       [Route("v1/b/test")]
       public object Get1()
       {
           return "{\"items\":[{\"name\":\"fru\",\"age\":\"12\"}]}";
       }
       //DELETE https://www.googleapis.com/storage/v1beta2/b/{bucket}
       [Route("v1/b/{bucket}")] 
        public void Delete(string bucket)
        {
            bucketService.Delete(bucket);
        }
        //PUT https://www.googleapis.com/storage/v1beta2/b/{bucket}
        [Route("v1/b/")] 
        public void Put(BucketInfo bucket)
        {
            bucketService.Save(BindToDomainModel(bucket));
        }
        //POST https://www.googleapis.com/storage/v1beta2/b 
        [Route("v1/b/")] 
        public BucketInfo Post(BucketInfo bucket)
        {
            Bucket bucketModel = BindToDomainModel(bucket);
            bucketService.Save(bucketModel);
            return BindToViewModel(bucketModel);
        }
        private BucketInfo BindToViewModel(Bucket domainBucket)
        {
            BucketInfo bucket = AutoMapper.Mapper.Map<Bucket, BucketInfo>(domainBucket);
            return bucket;

        }
        private Bucket BindToDomainModel(BucketInfo viewBucket)
        {
            Bucket bucket = AutoMapper.Mapper.Map<BucketInfo, Bucket>(viewBucket);
            bucket.Project = base.Project;
            return bucket;
        }
        static BucketsController()
        {
            AutoMapper.Mapper.CreateMap<BucketInfo, Bucket>();
            AutoMapper.Mapper.CreateMap<Bucket, BucketInfo>();
        }

      
    }
}